set seed 21112023

***THIS CODE WILL GENERATE BOOTSTRAP SAMPLES, WHICH WE SAVE, THEN ESTIMATE IN A LATER DO FILE
**ALLOWS US TO RUN ESTIMATION ON MULTIPLE COMPUTERS (WHILE FIXING SEED)
local bsamplesize = 100

**************Decomposition Sample

use "$working/Demand_TFPQIV_Qklme_2lags_sampleFS", clear
merge 1:1 co_code1 year using "$working/ProdQ_2lags_new_klme_sampleSS"

generate mid_s = 1 if _merge==3 // D and SS
replace mid_s = 2 if _merge==1 // D only
replace mid_s = 3 if _merge==2 // SS only

drop _merge

merge  1:1 co_code1 year using "$working/ProdQ_new_klme_2lags_sampleFS"

generate samples = 1 if _merge==3 & mid_s ==1 // D, FS, SS
replace samples = 2 if _merge==3 & mid_s==2 // D and FS
replace samples = 3 if _merge==3 & mid_s==3 // SS and FS

replace samples = 4 if _merge==1 & mid_s==1 // D and SS only
replace samples  = 5 if _merge==1 & mid_s==2 // D only
replace samples  = 6 if _merge==1 & mid_s==3 // SS only

replace samples = 7 if _merge==2 // FS only

tabulate samples

**Samples 2 is too rare: put into 1 
replace samples = 1 if samples==2
drop _merge
drop mid_s

sum
**grab the products that are just in FS
preserve
	merge 1:m co_code1 year using "$working/ProdQ_new_klme_2lags_sampleFS_prod"
	keep if _merge==3 & samples==3 | samples==7 | samples==6
	drop _merge
	tempfile t1
	tabulate samples
	save `t1', replace
restore

merge 1:m co_code1 year using "$working/Demand_TFPQIV_Qklme_2lags_sampleFS_prod"
drop if _merge==1 // These are products that are only in FS, not demand
drop _merge
append using `t1'

preserve

	collapse (mean) samples, by(co_code1 year)

	sum
	
	tabulate samples

restore
	
save "$working/sample_ProdQ_TFPQIV_2lags", replace

forvalues bs = 1(1)`bsamplesize' {
	clear
	***Grab bootstrap samples
	use "$working/sample_ProdQ_TFPQIV_2lags"
	bsample,  strata(samples) cluster(co_code1) idcluster(bs_co_code1)
	save "$BS_fold_old/record/Qklme/2lags/bssample_`bs'", replace
}
